using System;
using Edge.Business.Managers;
using Edge.Common.Services;
using Edge.Business.Entities;

namespace Edge.Business.Security
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="IT">id type</typeparam>
    /// <typeparam name="ET">entity type</typeparam>
    /// <typeparam name="EMT">entity manager type</typeparam>
    [Serializable]
    public class BaseObjectHolder<IT, ET, EMT>
        where ET : EntityWithStat<IT>
        where EMT : IAbstractManager<ET, IT>
    {
        private IT id;
        private bool isNull = false;

        public BaseObjectHolder(IT id)
        {
            this.id = id;
        }


        public BaseObjectHolder(ET entity)
        {
            SetEntity(entity);
        }

        public ET Object
        {
            get
            {
                if (isNull)
                    return null;

                return Locator.GetService<EMT>().Load(id);
            }
            set
            {
                SetEntity(value);
            }
        }

        private void SetEntity(ET value)
        {
            if (value == null)
            {
                isNull = true;
            }
            else
            {
                isNull = false;
                id = value.Id;
            }
        }


        public IT Id
        {
            get { return id; }
            set { id = value; }
        }
    }
}